package com.example.bookmanagersystem.controller;

import com.example.bookmanagersystem.service.BookService;
import com.example.bookmanagersystem.service.BorrowService;
import com.example.bookmanagersystem.service.ReaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/borrows")
public class BorrowController {
    @Autowired
    private BorrowService borrowService;

    @Autowired
    private BookService bookService;

    @Autowired
    private ReaderService readerService;

    // 借阅记录列表
    @GetMapping
    public String listBorrows(Model model) {
        model.addAttribute("records", borrowService.getAllBorrowRecords());
        return "borrows/list";
    }

    // 跳转到借书页面
    @GetMapping("/new")
    public String showBorrowForm(Model model) {
        model.addAttribute("books", bookService.getAvailableBooks());
        model.addAttribute("readers", readerService.getAllReaders());
        return "borrows/borrow-form";
    }

    // 借书
    @PostMapping("/borrow")
    public String borrowBook(@RequestParam Long bookId, @RequestParam Long readerId, RedirectAttributes redirectAttributes) {
        try {
            borrowService.borrowBook(bookId, readerId);
            redirectAttributes.addFlashAttribute("message", "借书成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/borrows";
    }

    // 还书
    @GetMapping("/return/{id}")
    public String returnBook(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            borrowService.returnBook(id);
            redirectAttributes.addFlashAttribute("message", "还书成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/borrows";
    }

    // 未归还的借阅记录
    @GetMapping("/unreturned")
    public String listUnreturned(Model model) {
        model.addAttribute("records", borrowService.getUnreturnedRecords());
        return "borrows/unreturned";
    }
}